package com.collaboration.electron.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

/**
 * @author pinzi
 * @param
 * @return 无
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    DataSource dataSource;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
                .usersByUsernameQuery("SELECT user_name, user_password, enabled " + "FROM u WHERE user_name = ?")
                .authoritiesByUsernameQuery("SELECT user_name, role " + "FROM u WHERE user_name = ?")
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user").hasRole("USER")
                .antMatchers("/product").hasRole("USER")
                .antMatchers("/save").hasRole("USER")
                .antMatchers("/h2").hasRole("ADMIN")
                .antMatchers("/*","/**","/register").permitAll()
                .and()
                .formLogin()
//                .loginPage("/login")
//                .loginProcessingUrl("/login/form")
                .and()
                .logout()
//                .logoutUrl("/logout")	/*自定义登出链接*/
//                .logout("/logout/form")
                .logoutSuccessUrl("/login") /*如果成功登出，需要跳转的页面*/

        ;

    }




}
